<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》,">





  <link rel="alternate" href="/atom.xml" title="卷柏的花期" type="application/atom+xml">






<meta name="description" content="本篇我们将介绍 JavaScript 中变量访问值的两种方式，然后详细介绍“执行栈”、“执行环境”、“作用域”、“作用域链”之间的关联。同时也附加说明执行环境对变量访问的影响。最后再介绍两种不同方式的垃圾回收机制，并重点说明在IE9以下错误的 DOM 引用会引发循环引用的问题，使得无用的 DOM 无法被清除，增大内存的消耗。">
<meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》">
<meta property="og:type" content="article">
<meta property="og:title" content="《JavaScript 高级程序设计》第四章：变量、作用域和内存问题">
<meta property="og:url" content="http://yoursite.com/2018/07/02/professional-javascript-chapter-4/index.html">
<meta property="og:site_name" content="卷柏的花期">
<meta property="og:description" content="本篇我们将介绍 JavaScript 中变量访问值的两种方式，然后详细介绍“执行栈”、“执行环境”、“作用域”、“作用域链”之间的关联。同时也附加说明执行环境对变量访问的影响。最后再介绍两种不同方式的垃圾回收机制，并重点说明在IE9以下错误的 DOM 引用会引发循环引用的问题，使得无用的 DOM 无法被清除，增大内存的消耗。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2018/07/02/professional-javascript-chapter-4/javascript.jpg">
<meta property="og:image" content="http://yoursite.com/2018/07/02/professional-javascript-chapter-4/yinyongleix.png">
<meta property="og:image" content="http://yoursite.com/2018/07/02/professional-javascript-chapter-4/scope_chain.png">
<meta property="og:image" content="http://yoursite.com/2018/07/02/professional-javascript-chapter-4/liucheng.png">
<meta property="og:updated_time" content="2018-12-31T09:27:28.041Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《JavaScript 高级程序设计》第四章：变量、作用域和内存问题">
<meta name="twitter:description" content="本篇我们将介绍 JavaScript 中变量访问值的两种方式，然后详细介绍“执行栈”、“执行环境”、“作用域”、“作用域链”之间的关联。同时也附加说明执行环境对变量访问的影响。最后再介绍两种不同方式的垃圾回收机制，并重点说明在IE9以下错误的 DOM 引用会引发循环引用的问题，使得无用的 DOM 无法被清除，增大内存的消耗。">
<meta name="twitter:image" content="http://yoursite.com/2018/07/02/professional-javascript-chapter-4/javascript.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/07/02/professional-javascript-chapter-4/">





  <title>《JavaScript 高级程序设计》第四章：变量、作用域和内存问题 | 卷柏的花期</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband">
    <a href="https://gitee.com/Selaginella/" target="_blank" style="position:absolute;right:0;top:0;border:none"><img src="https://gitee.com/Selaginella/Selaginella/widgets/widget_1.svg" alt="Fork me on Gitee"></a>
    </div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">卷柏的花期</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">随风而动，九死还生</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-source">
          <a href="/source/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-flask"></i> <br>
            
            资源
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/07/02/professional-javascript-chapter-4/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Selaginella">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="卷柏的花期">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">《JavaScript 高级程序设计》第四章：变量、作用域和内存问题</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-07-02T06:33:00+08:00">
                2018-07-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote class="blockquote-center"><img src="/2018/07/02/professional-javascript-chapter-4/javascript.jpg" alt="&#39;JavaScript 高级程序设计&#39;">本篇我们将介绍 JavaScript 中变量访问值的两种方式，然后详细介绍“执行栈”、“执行环境”、“作用域”、“作用域链”之间的关联。同时也附加说明执行环境对变量访问的影响。最后再介绍两种不同方式的垃圾回收机制，并重点说明在IE9以下错误的 DOM 引用会引发循环引用的问题，使得无用的 DOM 无法被清除，增大内存的消耗。</blockquote>

<a id="more"></a>
<h2 id="变量的引用"><a href="#变量的引用" class="headerlink" title="变量的引用"></a>变量的引用</h2><p>当一个变量保存了基本数据类型时，此时对于变量的操作（赋值，运算）就是操作这个基本数据的本身，就算是赋值操作，赋值时拷贝后的值与之前的值也是相互独立互不影响的。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="keyword">var</span> b = a</span><br><span class="line">b++;</span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">//1</span></span><br><span class="line"><span class="built_in">console</span>.log(b); <span class="comment">//2</span></span><br></pre></td></tr></table></figure></p>
<p>这非常好理解，但是如果一个变量保存的是一个引用类型的数据，例如对象，那么情况将会不同，这是因为变量保存的并不是对象本身，而是其在内存中的地址（指针），所以当对引用类型进行赋值时，虽然也会进行拷贝，但是这个拷贝后的值只是一个指针，它们两个最终指向的都是对同一个对象的引用，因此便会存在相互影响的问题。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line"><span class="keyword">var</span> copyObj = obj;</span><br><span class="line">obj.name = <span class="string">'test'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(obj2.name); <span class="comment">//test</span></span><br></pre></td></tr></table></figure>
<p>用图表示就是如下关系：<br><img src="/2018/07/02/professional-javascript-chapter-4/yinyongleix.png" alt="&#39;引用联系&#39;"><br>通过具体的事例再来感受这两者的不同：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">PersonnelInfo</span>(<span class="params">age, info</span>) </span>&#123;</span><br><span class="line">    age = <span class="number">10</span>;</span><br><span class="line">    info.name = <span class="string">"cheng"</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> info = &#123;&#125;;</span><br><span class="line"><span class="keyword">var</span> age = <span class="number">0</span>;</span><br><span class="line">PersonnelInfo(age, info);</span><br><span class="line"><span class="built_in">console</span>.log(age);</span><br><span class="line"><span class="built_in">console</span>.log(info);</span><br></pre></td></tr></table></figure>
<p>由此我们可以得出变量的访问有两种，一种是“按值访问”，另一种则是“按引用访问”，按值访问操作变量操作的就是值的本身，在进行赋值的时候也是相互独立互不影响的，而按引用访问，再进行赋值的时候，实际上多个变量访问的对象依然是同一个。</p>
<blockquote>
<p>一般来说我们会将固定大小的值(例如基本数据类型)保存到栈内存中，将不能固定大小的值(例如对象，数组等)保存到堆内存中，这样的区分也是更好的利用内存空间，提高执行效率。</p>
</blockquote>
<h2 id="执行环境及作用域"><a href="#执行环境及作用域" class="headerlink" title="执行环境及作用域"></a>执行环境及作用域</h2><p>变量的访问有两种，“按值访问”以及“按引用访问”，而执行环境(Execution Context) 则形成了作用域，作用域又确定了变量或函数是否有权访问其它环境中的数据。也就是说执行环境确定了某些标识符是否能被访问。</p>
<p>每个执行环境都会有个与之对应的变量对象(Variable Object)，变量对象用于管理和保存当前环境中的变量以及函数(标识符)。当从一个执行环境进入到另一个执行环境时，首先便会创建变量对象，然后该执行环境会被加入到当前的执行栈中进行执行，如果执行完毕则会从执行栈中弹出，并且该环境中的代码、函数以及变量也都会被销毁。</p>
<p>在JavaScript中执行环境主要的有两种：全局执行环境，函数执行环境。全局执行环境绑定在 WEB浏览器顶层宿主对象 window上，也就是说我们在全局执行环境中声明的变量或者函数都会将作为 window对象的属性或者是方法，也因此只有在退出浏览器或关闭WEB页面才会销毁全局执行环境。<br>函数的执行环境也是一种局部执行环境，变量对象会比较特殊，我们更多的将其称之为“活动对象(Active Object)”，它默认保存的一个标识符就是 <code>arguments</code>，而 <code>arguments</code> 中保存的便是该函数的参数。</p>
<p>当执行环境被加入到执行栈中进行执行的时候，JS引擎会根据变量对象来解析标识符，首先它会查找当前执行环境中的标识符是否在变量对象中有定义，如果有则取得标识符的值进行下一步操作，如果没有，则向上进入到上一级执行环境，访问其变量对象，依次类推，像这样对不同的环境不同的变量对象进行访问的路径，我们可以称之为作用域链(scope chain)。</p>
<p><img src="/2018/07/02/professional-javascript-chapter-4/scope_chain.png" alt="&#39;作用域&#39;"><br>因此，所谓的标识符解析实际上就是沿着作用域链进行标识符的查找。<br>作用域链的访问只能由前向后，由下向上，而不能反方向访问，具体可见事例代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="number">1</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">method</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> y = <span class="number">2</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(x);</span><br><span class="line">&#125;</span><br><span class="line">method();</span><br><span class="line"><span class="built_in">console</span>.log(y); <span class="comment">//Uncaught ReferenceError: y is not defined</span></span><br></pre></td></tr></table></figure>
<p>也可见下图：<br><img src="/2018/07/02/professional-javascript-chapter-4/liucheng.png" alt=""></p>
<h2 id="作用域链延长"><a href="#作用域链延长" class="headerlink" title="作用域链延长"></a>作用域链延长</h2><p>在 JavaScript中有的语句可以在当前的作用域链前端增加一个变量对象，从而延长作用域链。<br>对于 <code>with</code> 语句它会将指定的对象作为变量对象添加至作用域链的前端。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">buildUrl</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> search = <span class="string">'?debug=true'</span>;</span><br><span class="line">    <span class="keyword">with</span>(location)&#123;</span><br><span class="line">        var url = href +　search; #注意with并没有作用域。</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> url;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>而对于 <code>catch</code> 语句而言则会创建一个新的对象，然后添加至当前作用域链的前端，在这个变量对象中保存的主要是错误对象 <code>Error</code> 的相关信息，例如 name，message等。</p>
<h2 id="块级作用域"><a href="#块级作用域" class="headerlink" title="块级作用域"></a>块级作用域</h2><p>JavaScript (ES5) 中并不存在块级作用域，ES5支持的作用域跟执行环境相同，主要有函数（局部）作用域、全局作用域。<br>声明变量时，如果使用 <code>var</code> 关键字，则所声明的变量添加至当前执行环境中的变量对象上，如果没有使用 <code>var</code> 关键字，则默认添加至全局执行环境的的变量对象上。</p>
<blockquote>
<p>不论是全局作用域还是局部作用域，声明变量时正确的操作都是使用 <code>var</code> 关键字去声明。</p>
</blockquote>
<h2 id="垃圾回收机制"><a href="#垃圾回收机制" class="headerlink" title="垃圾回收机制"></a>垃圾回收机制</h2><h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><p>JavaScript支持自动的垃圾回收机制，而不像C，C++那样需要手动的跟踪内存的使用情况，而所谓的自动垃圾回收机制，其本质原理非常简单，那就是每隔一段时间，周期性的检查程序的执行情况，将不在使用的标识符其所占据的内存释放，或者自动分配程序执行期间所需要的内存空间，这样开发人员只需关注业务功能代码，无需过多关心内存的使用情况。</p>
<p>当我们明白垃圾回收机制的大致原理时，那么如何确定一个标识符，其生命周期是否已经结束，就时垃圾自动回收的功能核心。</p>
<h3 id="标记清除"><a href="#标记清除" class="headerlink" title="标记清除"></a>标记清除</h3><p>主流浏览器厂商，基本都时采用 “标记清除(mark and sweep)”的方式来标识那些变量可以被回收，那些变量还具有引用关系不能被回收。<br>其大致思路时当一个变量进入执行环境时，会为它添加一个标志位，用于说明该变量进入了该环境，原则上永远不能释放进入环境中的变量，因为执行流程进入到相应的环境就有可能会用得到。而当变量离开环境时，则再将其标志置为离开状态。<br>这种标志位的记录方式有很多种，你可以通过翻转某一个位来记录一个变量何时进入环境，何时离开环境，也可以使用 map表的方式来分别记录进入与离开时的状态信息。<br>当JS的垃圾回收机制运行的时候，它会给存储在内存中的所有变量都加上标记（可以使用任何方式）然后它会去掉全局环境中的以及执行环境中具有引用关系的变量标记，而在此之后在被添加标记（可以认为是离开标记）都被视为准备删除的变量，原因是这些变量已经不需要再被访问了。<br>简单的来概括，那就时当变量进入环境时，其标记为1，离开时置为0，然后JS的垃圾回收机制每隔一段时间来扫描，将标记为0的变量进行释放。<br>用代码来表示如下：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> status = <span class="number">1</span> <span class="comment">//进入环境</span></span><br><span class="line"></span><br><span class="line">status = <span class="literal">null</span> <span class="comment">//离开环境，或者为Null的时候，马上被垃圾回收机制回收。</span></span><br></pre></td></tr></table></figure></p>
<h3 id="引用计数"><a href="#引用计数" class="headerlink" title="引用计数"></a>引用计数</h3><p>“引用计数 (reference counting)”。引用计数实际上就是对值的一种计数标记，当我们定义一个变量并为它赋值一个引用类型时，这个引用类型的值其引用次数就默认为1，当这个值还被其它的变量所引用，则引用次数加1。相反当引用了这个值的变量引用了别的值，则其引用次数减1。当这个值的引用次数为0时，便说明这个值已经以及没有被其它变量引用了，此时便可以将其所占据的内存释放出来。</p>
<p>引用计数的方式有一个非常严重的问题，那就是“循环引用”，当A的值有对B值的引用，而B值中也有对A值的引用时就会发生循环引用。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">problem</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> ObjectA = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">    <span class="keyword">var</span> ObjectB = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">    ObjectA.A = ObjectB;</span><br><span class="line">    ObjectB.B = ObjectA;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在这个事例中变量 ObjectA 与 ObjectB的值分别被引用了两次，第一次是声明变量并赋值的时候，第二次则是它们各自的属性进行了交叉引用。所以此时这两个对象的值引用次数就时 2，如果在标记清除的策略中并没用什么问题，但是在引用计数的方式下，ObjectA与ObjectB将在函数执行完毕后还会存在，因为它们的引用次数永远不会为0。假如这个函数被重复执行多次，那么就会导致更多的内存空间得不到回收。</p>
<p>采用“引用计数”方式的浏览器都非常古老了，主要是 Netspace Navigator 3.0 以及之前，所以不需要太担心，但是了解下还是非常有必要的，这是因为在IE9之前，对于JavaScript中原生对象采用的是标记清除方式，但是对于非原生对象，例如BOM，DOM等垃圾回收机制依然还是引用计数策略，所以如果需要兼容IE9以下版本的浏览器，在操作非原生对象时，就有可能会出现循环引用的问题。</p>
<p>事例代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> element = <span class="built_in">document</span>.getElementById(<span class="string">'element'</span>);</span><br><span class="line"><span class="keyword">var</span> myObject = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line"></span><br><span class="line">myObject.element = element;</span><br><span class="line">element.hostObject = myObject;</span><br></pre></td></tr></table></figure>
<p>对于这种情况，我们最好在书写代码的时候就要尽量避免，如果难以避免，则在程序执行完成以后也要记得手动释放。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">myObject.element = <span class="literal">null</span>;</span><br><span class="line">element.hostObject = <span class="literal">null</span>;</span><br></pre></td></tr></table></figure>
<h3 id="性能问题"><a href="#性能问题" class="headerlink" title="性能问题"></a>性能问题</h3><p>我们知道垃圾回收机制是周期性的进行运行的，因此确定垃圾收集的时间间隔是一个非常重要的问题。<br>在IE7之前，IE的回收机制都是根据内存的分配量进行的，具体一点就是256个变量，4096个对象（或数组）字面量和数组元素(slot)或者64KB的字符串，达到上述的任何一个临界值，垃圾收集器就会运行。这种实现方式的问题在于如果一个脚本具有非常多的变量，那么脚本很可能会在其生命周期中一直保有那么多的变量。这样一来，垃圾收集器就不得不频繁的执行，从而影响了正常的程序执行。<br>到了IE7后，微软重写了IE浏览器的垃圾回收机制，触发垃圾收集的变量分配、字面量和（或）数组元素的临界值被调整为动态修正，其各项临界值在初始时与IE6及之前的版本相同，如果垃圾收集例程回收的内存分配量低于15%，则变量、字面量和（或）数组元素的临界值就会加倍，如果例程回收了85%的内存分配量，则再将各临界值重置为默认值。</p>
<p>在日常编码时还有另一种方式可以很好的提升执行的性能，那就是为不再使用到的变量赋值 <code>null</code> 来进行手动的释放。一般来说这种方式常用于全局变量，因为局部变量会由垃圾回收机制自行清理。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">doSomething</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> obj = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">    <span class="keyword">return</span> obj.name = <span class="string">'csutom'</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> global_var = doSomething();</span><br><span class="line"></span><br><span class="line"><span class="comment">//...</span></span><br><span class="line"></span><br><span class="line">global_var = <span class="literal">null</span>; <span class="comment">//当不用的时候最好记得手动释放</span></span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wx.jpg" alt="Selaginella 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Selaginella 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/读书笔记/" rel="tag"># 读书笔记</a>
          
            <a href="/tags/《JavaScript-高级程序设计》/" rel="tag"># 《JavaScript 高级程序设计》</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/06/25/nodejs-npm-manager/" rel="next" title="NodeJS学习：搭建私有NPM">
                <i class="fa fa-chevron-left"></i> NodeJS学习：搭建私有NPM
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/07/22/webpack-require-outline/" rel="prev" title="webpack - require 概要">
                webpack - require 概要 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTkxNC8xODQ2MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="Selaginella">
            
              <p class="site-author-name" itemprop="name">Selaginella</p>
              <p class="site-description motion-element" itemprop="description">知识在于积累，努力必有收获</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/shenguotao2015" target="_blank" title="gitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/Selaginella" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-telegram"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://www.cnblogs.com/HCJJ/" target="_blank" title="博客园">
                      
                        <i class="fa fa-fw fa-rss-square"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sgt_ah@163.com" target="_blank" title="Email">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#变量的引用"><span class="nav-number">1.</span> <span class="nav-text">变量的引用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#执行环境及作用域"><span class="nav-number">2.</span> <span class="nav-text">执行环境及作用域</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#作用域链延长"><span class="nav-number">3.</span> <span class="nav-text">作用域链延长</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#块级作用域"><span class="nav-number">4.</span> <span class="nav-text">块级作用域</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#垃圾回收机制"><span class="nav-number">5.</span> <span class="nav-text">垃圾回收机制</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#概述"><span class="nav-number">5.1.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#标记清除"><span class="nav-number">5.2.</span> <span class="nav-text">标记清除</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#引用计数"><span class="nav-number">5.3.</span> <span class="nav-text">引用计数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#性能问题"><span class="nav-number">5.4.</span> <span class="nav-text">性能问题</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Selaginella<span class="with-love"><i class="fa fa-heart"></i></span>Hexo 强力驱动</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>




















  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
